package com.nineclock.document.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.document.dto.DocUserCollaborationDTO;
import com.nineclock.document.mapper.DocCollaborationsMapper;
import com.nineclock.document.mapper.DocFileMapper;
import com.nineclock.document.pojo.DocCollaborations;
import com.nineclock.document.pojo.DocFile;
import com.nineclock.document.service.DocCollaborationsService;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class DocCollaborationsServiceImpl implements DocCollaborationsService {

    @Autowired
    private SysUserFeign sysUserFeign;
    @Autowired
    private DocFileMapper fileMapper;
    @Autowired
    private DocCollaborationsMapper collaborationsMapper;

    @Override
    public List<DocUserCollaborationDTO> pagingUsers(Long id) {
        //参数校验
        if(id == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //查询当前企业的所有员工 ---> 拥有者, 协作者
        List<SysCompanyUserDTO> allCompanyUser = sysUserFeign.queryAllCompanyUser().getData();

        //根据文档ID查询文档信息
        DocFile docFile = fileMapper.selectById(id);
        Long createUserId = docFile.getCreateUserId();

        //根据文档ID查询文档协作者
        LambdaQueryWrapper<DocCollaborations> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DocCollaborations::getFileId, id);
        List<DocCollaborations> collList = collaborationsMapper.selectList(wrapper);

        List<Long> collIds = collList.stream().map(docCollaborations -> {
            return docCollaborations.getCollaborationId();//协作者ID
        }).collect(Collectors.toList());

        //组装数据
        List<DocUserCollaborationDTO> collaborationDTOList = allCompanyUser.stream().map(sysCompanyUserDTO -> {

            DocUserCollaborationDTO collaborationDTO = new DocUserCollaborationDTO();
            collaborationDTO.setId(sysCompanyUserDTO.getId());
            collaborationDTO.setImgUrl(sysCompanyUserDTO.getImageUrl());
            collaborationDTO.setPhone(sysCompanyUserDTO.getMobile());
            collaborationDTO.setUsername(sysCompanyUserDTO.getUserName());

            Long companyUserId = sysCompanyUserDTO.getId();

            //组装状态标识
            int state = createUserId == companyUserId ? 1 : collIds.contains(companyUserId) ? 2 : 0;
            collaborationDTO.setState(state);
            return collaborationDTO;
        }).collect(Collectors.toList());

        return collaborationDTOList;
    }

}
